package com.difsonapps.android.marker.activities;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.adapters.PhotoPagerAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.beans.Video;
import com.difsonapps.android.marker.fragments.PhotosFragment;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class PhotoViewActivity extends Activity {
    private static final String TAG = PhotoViewActivity.class.getSimpleName();
	private PhotoPagerAdapter adapter;
	private ViewPager viewPager;
	
	ArrayList<Photo> photos = new ArrayList<Photo>();
	ArrayList<Video> videos = new ArrayList<Video>();
	
	private int offsetBefore = 0;
	private int offsetAfter = 0;
	
	private boolean loadTestDatas = true;
	boolean modePhotos = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo_view);
		viewPager = (ViewPager) findViewById(R.id.pager);
		//getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));


		Intent i = getIntent();
		int position = i.getIntExtra("position", 0);
		if(i.hasExtra("mode_photo")) modePhotos = i.getBooleanExtra("mode_photo", true);
		if(modePhotos){
			ArrayList<Photo> photosReaded = i.getParcelableArrayListExtra("photos");
			if(photosReaded==null || photosReaded.isEmpty()){
				photosReaded = new ArrayList<Photo>();
				Photo photo = i.getParcelableExtra("photo");
				if(photo!=null) photosReaded.add(photo);			
				if(loadTestDatas && photosReaded.isEmpty()) {
					for(int pos=0;pos<1;pos++){			
						Photo p = new Photo();
						p.setAvgMarks(pos);
						p.setId(72+pos);
						p.setDescription("This is an example of description "+pos);
						p.setTitle("Title of photo "+pos);
						p.setNbMarks(pos);
						p.setImage(MarkerUtil.buildImageUrl("1360671997Lighthouse.jpg", AppConstant.IMAGES_FOLDER, null));
						photosReaded.add(p);
						//toast("Added : "+p.getTitle());
					}
				}
			}
			
			photos = photosReaded;
			for(Photo p : photosReaded){
				if(offsetBefore==0||p.getId()<offsetBefore) offsetBefore = p.getId();
				if(offsetAfter==0||p.getId()>offsetAfter) offsetAfter = p.getId();
			}
			adapter = new PhotoPagerAdapter(PhotoViewActivity.this, photos);
		}else{
			ArrayList<Video> videosReaded = i.getParcelableArrayListExtra("videos");
			if(videosReaded==null || videosReaded.isEmpty()){
				videosReaded = new ArrayList<Video>();
				Video video = i.getParcelableExtra("video");
				if(video!=null) videosReaded.add(video);
			}
			
			videos = videosReaded;
			for(Video p : videosReaded){
				if(offsetBefore==0||p.getId()<offsetBefore) offsetBefore = p.getId();
				if(offsetAfter==0||p.getId()>offsetAfter) offsetAfter = p.getId();
			}
			adapter = new PhotoPagerAdapter(PhotoViewActivity.this, videos, false);
		}

		viewPager.setAdapter(adapter);

		// displaying selected image first
		viewPager.setCurrentItem(position);
		if(!modePhotos) return;
		loadBefore();
		loadAfter();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.photo_view, menu);
		return true;
	}
	
	public void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	

	public void loadBefore(){
		if(offsetBefore<=0) return;
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+offsetBefore);
        params.put("limit", ""+AppConstant.MAX_PHOTO_LOADED);
        String url = MarkerUtil.buildUrl(AppConstant.photosBeforeInAlbumUrl, params);
        Log.d(TAG, url);
        toast("load before : "+url);
        
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(url);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonPhotosBefore(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
        } else {
            // making fresh volley request and getting json
            CustomRequest jsonReq = new CustomRequest(Method.GET,
            		url, null, new Response.Listener<JSONObject>() {
 
                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                            	parseJsonPhotosBefore(response);
                            }
                        }
                    }, new Response.ErrorListener() {
 
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });
 
            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }
	}
	
	private void parseJsonPhotosBefore(JSONObject response) {
    	toast("Response : "+response.toString());
    	Log.d("Json Before photo", response.toString());
        try {
            JSONArray feedArray = response.getJSONArray("photos");
            int currentPage = viewPager.getCurrentItem();
            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);
                Photo item = Photo.parseFromJsonObject(feedObj);
                photos.add(0, item);
                if(offsetBefore==0 || offsetBefore>item.getId()) offsetBefore = item.getId();                
            }
            if(feedArray!=null&&feedArray.length()>0) loadBefore();//Iteratf call
            // notify data changes to list adapater
            adapter.notifyDataSetChanged();
            if(feedArray.length()>0) viewPager.setCurrentItem(currentPage+feedArray.length(), false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
	public void loadAfter(){
		if(offsetAfter<=0) return;
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+offsetAfter);
        params.put("limit", ""+AppConstant.MAX_PHOTO_LOADED);
        String url = MarkerUtil.buildUrl(AppConstant.photosAfterInAlbumUrl, params);
        Log.d(TAG, url);
        toast("load after : "+url);
        
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(url);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonPhotosAfter(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
        } else {
            // making fresh volley request and getting json
            CustomRequest jsonReq = new CustomRequest(Method.GET,
            		url, null, new Response.Listener<JSONObject>() {
 
                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                            	parseJsonPhotosAfter(response);
                            }
                        }
                    }, new Response.ErrorListener() {
 
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });
 
            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }
	}
	
	private void parseJsonPhotosAfter(JSONObject response) {
    	toast("Response : "+response.toString());
        try {
            JSONArray feedArray = response.getJSONArray("photos");
            //int currentPage = viewPager.getCurrentItem();
            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);
                
                Photo item = Photo.parseFromJsonObject(feedObj);
                photos.add(item);//Add at the end
                if(offsetAfter==0 || offsetAfter<item.getId()) offsetAfter = item.getId();                
            }
            if(feedArray!=null&&feedArray.length()>0) loadAfter();//Iteratf call
            // notify data changes to list adapater
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
